package com.century.sjt.fragment;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.Topic.MyTopicDetail;
import com.century.sjt.adapter.MySocialZoneAdapter;
import com.century.sjt.entity.Comment;
import com.century.sjt.entity.ItemBean;
import com.century.sjt.entity.Praise;
import com.century.sjt.entity.SjtUser;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by luodong on 15/7/21.
 */
public class SocialTabSquareFragment extends Fragment {
    final List<ItemBean> dataList = new ArrayList<>();

    private MySocialZoneAdapter mySocialZoneAdapter;

    private RequestQueue mQueue;

    public static Handler mHandler;
//    private Button loadMore;

    private int SEND_LOAD_MORE_NUM = 1;                       //话题翻页的页数

    private ListView mListViewForScrollView;

    private SwipeRefreshLayout mSwipeLayout;        //刷新组件
    private Boolean isDataChangeOk = true;        //是否更新成功

    private List<Comment> mCommentList = new ArrayList<>();
    private List<Praise> mPraiseList = new ArrayList<>();
    private String mPraiseNameList = "";
    private SjtUser mUser;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_social_tab_square, container, false);

        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        mySocialZoneAdapter.notifyDataSetChanged();
                        mSwipeLayout.setRefreshing(false);
                        break;
                    case 2:
                        isDataChangeOk = true;
                        dataList.clear();
                        SEND_LOAD_MORE_NUM = 1;
                        FriendsTopic();
                        break;
                    case 3:
                        if (isDataChangeOk) {
                            mSwipeLayout.setRefreshing(true);
                            SEND_LOAD_MORE_NUM++;
                            FriendsTopic();
                            break;
                        }

                }
            }
        };
        mQueue = Volley.newRequestQueue(getActivity());
        mListViewForScrollView = (ListView) view.findViewById(R.id.lv_my_social_zone_new_mian);
        mySocialZoneAdapter = new MySocialZoneAdapter(getActivity(), dataList, mQueue,mHandler);

        mListViewForScrollView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ItemBean itemBean = dataList.get(position);
                String topicId = itemBean.topicId;
                Intent intent = new Intent(getActivity(), MyTopicDetail.class);
                intent.putExtra("topicId", topicId);
                intent.putExtra("option", "");
                startActivity(intent);
                getActivity().overridePendingTransition(R.animator.in_from_right, R.animator.out_to_left);
            }
        });


        mListViewForScrollView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                // 当不滚动时
                if (i == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        Message msg = new Message();
                        msg.what = 3;
                        mHandler.sendMessage(msg);
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
//        //显示更多
//        View bottomView=getActivity().getLayoutInflater().inflate(R.layout.social_zone_listview_bottom, null);
//        loadMore=(Button)bottomView.findViewById(R.id.social_zone_listview_bottom_load);
//        loadMore.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                loadMore.setEnabled(false);
//                loadMore.setText("加载中");
//                SEND_LOAD_MORE_NUM++;
//                mHandler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        loadData();
//                        Message msg = new Message();
//                        msg.what = 1;
//                        mHandler.sendMessage(msg);
//
//                    }
//                }, 2000);
//            }
//        });
//
//        mListViewForScrollView.addFooterView(bottomView);
        FriendsTopic();
        mListViewForScrollView.setAdapter(mySocialZoneAdapter);


        //刷新组件
        mSwipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.my_social_zone_new_refesh);
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
            }
        });
        mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        return view;

    }

    /**
     * 获取获取话题
     * @param shopId
     */
    private void FriendsTopic() {
        isDataChangeOk = false;
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.error_please_waitting), getActivity());
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.FriendsTopic, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                isDataChangeOk = true;
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("获取话题", response, 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
//                    JSONObject topicList = data.getJSONObject("topicList");
//                    JSONObject user = topicList.getJSONObject("user");
                    if (code.equals("200")) {//成功
                        JSONObject data = res.getJSONObject("data");
                        if(data.length()!= Constant.PAGESIZE){
                            isDataChangeOk = false;
                        }
                        JSONArray mTopicList = data.getJSONArray("topicList");
                        for (int i = 0; i < mTopicList.length(); i++) {
                            mPraiseList.clear();
                            mCommentList.clear();
                            mPraiseNameList = "";
                            JSONObject topicList = (JSONObject) mTopicList.get(i);
                            String topicId = topicList.getString("sysId");
                            String content = topicList.getString("content");
                            String createDateTime = topicList.getString("createDateTime");
//                            String themePic1 = topicList.getString("themePic1");
//                            String themePic2 = topicList.getString("themePic2");
//                            String themePic3 = topicList.getString("themePic3");
//                            String themePic4 = topicList.getString("themePic4");
//                            String themePic5 = topicList.getString("themePic5");
//                            String themePic6 = topicList.getString("themePic6");
//                            String themePic7 = topicList.getString("themePic7");
//                            String themePic8 = topicList.getString("themePic8");
//                            String themePic9 = topicList.getString("themePic9");
                            String themePic = topicList.getString("themePic");
                            int praiseNum = topicList.getInt("praiseNum");
                            int commentNum = topicList.getInt("commentNum");
                            JSONObject user = topicList.getJSONObject("user");
                            mUser = new SjtUser();
                            mUser.setSysid(user.getString("sysId"));
                            mUser.setNickName(user.getString("nickName"));
                            mUser.setImage(user.getString("image"));
                            String shareUrl = topicList.getString("shareUrl");
//                            Log.e("image1", image);
//                            Log.e("获取话题", createDateTime);
                            JSONArray praiseList = topicList.getJSONArray("praiseList");
                            for (int j = 0;j<praiseList.length();j++){
                                JSONObject praise =(JSONObject) praiseList.get(j);
                                JSONObject auser = (JSONObject) praise.getJSONObject("user");
                                SjtUser user1 = new SjtUser();
                                user1.setSysid(auser.getString("sysId"));
                                user1.setNickName(auser.getString("nickName"));
                                user1.setImage(auser.getString("image"));
                                if (j>0){
                                    String mName = "、"+user1.getNickName();
                                    mPraiseNameList+=mName;
                                }else {
                                    mPraiseNameList+=user1.getNickName()+" ";
                                }

                                Praise praise1 = new Praise();
                                praise1.setSysId(praise.getString("sysId"));
                                praise1.setContent(praise.getString("content"));
                                praise1.setCreateDateTime(praise.getString("createDateTime"));
                                praise1.setUser(user1);
                                mPraiseList.add(praise1);
                            }
                            JSONArray commentList = topicList.getJSONArray("commentList");
                            for (int j = 0;j<commentList.length();j++){
                                JSONObject comment =(JSONObject) commentList.get(j);
                                JSONObject auser = (JSONObject) comment.getJSONObject("user");
                                SjtUser user1 = new SjtUser();
                                user1.setSysid(auser.getString("sysId"));
                                user1.setNickName(auser.getString("nickName"));
                                user1.setImage(auser.getString("image"));
                                Comment comment1 = new Comment();
                                comment1.setSysId(comment.getString("sysId"));
                                comment1.setContent(comment.getString("content"));
                                comment1.setCreateDateTime(comment.getString("createDateTime"));
                                comment1.setUser(user1);
                                mCommentList.add(comment1);
                            }
                            dataList.add(new ItemBean(mPraiseList,mPraiseNameList, mCommentList, createDateTime, content, themePic,
                                    topicId, praiseNum, commentNum,shareUrl,mUser));
                            // 设置适配器

                        }
//                        loadMore.setText("加载更多");
//                        loadMore.setEnabled(true);
//                        Toast.makeText(MySocialZoneActivity.this, "加载中", Toast.LENGTH_LONG).show();

                    } else {//失败
                        isDataChangeOk = false;
//                        loadMore.setText("没有更多话题");
//                        loadMore.setEnabled(false);
//                        Toast.makeText(MySocialZoneActivity.this, "没有更多话题", Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();

                    Toast.makeText(getActivity(), getResources().getString(R.string.error_service), Toast.LENGTH_LONG).show();
                }
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), getActivity(), 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                String num = String.valueOf(SEND_LOAD_MORE_NUM);
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getActivity().getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("paging.currentPage", num);
                map.put("paging.pageSize", Constant.PAGESIZE + "");
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getActivity().getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
